<?php

class VerifyLogin extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('costumer', '', TRUE);
        $this->load->model('ym');
        $this->load->model('user');
        $this->load->model('document');
    }

    function index() {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('username', 'Username', 'trim|required|xxs_clean');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|xxs_clean|callback_check_database');

        if ($this->form_validation->run() == FALSE) {
            $data['yms'] = $this->ym->admin();
            $data['documents'] = $this->document->index();
            $data['content'] = 'login/costumer';
            $this->load->view('template/login', $data);
        } else {
            redirect('costumers/index', 'refresh');
        }
    }

    function check_database($password) {
        $username = $this->input->post('username');
        $result = $this->costumer->login($username, $password);

        if ($result) {
            $sess_array = array();
            foreach ($result as $row) {
                if ($row->status == 1 && $row->user_confirmation == 2) {
                    $sess_array = array(
                        'id' => $row->id,
                        'username' => $row->username
                    );
                    $this->session->set_userdata('logged_in', $sess_array);
                } else {
                     $this->form_validation->set_message('check_database', 'Please confirm your e-mail account');
            return false;
                }
            }
            return TRUE;
        } else {
            $this->form_validation->set_message('check_database', 'Invailid username or password');
            return false;
        }
    }

}